#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@File: SqlDealApp.py
@Author: lijk34925 
@Date: 2024/9/4 15:02
@desc: 请补充本模块功能说明
"""
import re

from BladeFerm.databases import DB_APP
from BladeFerm.databases.DealSql.MakeSql import SQLCheck
from BladeFerm.Lib.Common import logger


def parse_sql(sql, filter_flag: str = "_time"):
    """
    解析insert的sql语句，去除时间相关字段
    :param sql:
    :param filter_flag:
    :return:
    """
    sql_check = SQLCheck()
    sql_check.get_basic_detail(sql, filter_flag)
    sql_check.remove_target_key(filter_flag)
    return sql_check.new_sql


def check_sql_data_right(sql_text, **db_link_config):
    """
    批量解析insert的sql语句，去除时间相关字段
    :param sql_text:
    :return:
    """
    db_type = db_link_config.get("db_type", "oracle")
    DB_APP.make_db(**db_link_config)
    sql_check = SQLCheck()
    sql_check.db_app = DB_APP
    sql_check.get_basic_detail(sql_text, "insert")
    sql_check.get_table_dict()
    sql_check.check_table_data_right(db_type)


def read_sql_file(filename, encoding='utf-8'):
    with open(filename, 'r', encoding=encoding) as file:
        lines = file.readlines()
    lines = [line for line in lines if not (line.startswith('--') or line.startswith('#') or line.startswith('/*'))]
    contents = ''.join(lines)
    # 拆分sql,应该不会有select
    sql_pattern = re.compile(r'((SELECT|UPDATE|DELETE|INSERT|CREATE|ALTER|DROP|COMMIT).*?);(\s+)?$',
                             re.DOTALL | re.IGNORECASE | re.MULTILINE)
    sql_list_res = sql_pattern.findall(contents)
    if sql_list_res:
        # 新增去除 insert语句的time相关字段
        # sql_list = [parse_sql(unit[0].strip()) for unit in sql_list_res]
        sqls = [unit[0].strip() for unit in sql_list_res]
        logger.info(f'sql_list: {len(sqls)}')
        return sqls
    else:
        logger.error(f'文件{filename}中未找到有效的SQL语句')
        return []


if __name__ == '__main__':
    sql_filename = "C:\\Users\lijk34925\Desktop\专项测试\\temp\\SQLFILE.SQL"
    sql_list = read_sql_file(sql_filename, 'UTF-8')
    for item in sql_list:
        print(item)